class YHNetWorking {
  constructor(options) {
    this.url = true;
    //
    this.requestInterceptor = null;
    !!options &&
      !!options.requestInterceptor &&
      (this.requestInterceptor = options.requestInterceptor);
    //
    this.resInterceptor = null;
    !!options &&
      !!options.resInterceptor &&
      (this.resInterceptor = options.resInterceptor);
    //
    this.config = { headers: {} };
    !!options &&
      !!options.config &&
      (this.config = { ...options.headers, ...options.config });
  }
  //
  deleSpace(str) {
    let index = str.indexOf(" ");
    let res = str;
    while (index >= 0) {
      res = res.replace(" ", "");
    }
    return res;
  }
  //
  netTaskByConf(options) {
    if (this.requestInterceptor != null) {
      options = this.requestInterceptor(options);
    }
    return new Promise((resolve, reject) => {
      const thatApp = getApp();
      if (thatApp.globalData.netErrTips) {
        return console.error("netErrTips");
      }

      const that = this;
      const severAddress = options.config.host;
      const method = options.config.method;
      const sync = options.config.sync;
      let path = options.config.path;
      const port = options.config.port;
      path = this.deleSpace(path);
      console.log("severAddress - ", severAddress);
      if (path.indexOf("(") >= 0) {
        const params = options.params;
        if (!!params) {
          for (const key in params) {
            let val = params[key];
            path = path.replace(`(${key})`, val);
          }
        } else {
          reject(new EvalError(`restful api at ${path} need params !`));
        }
      }
      //   console.log("path res = ", path);
      var turl = port
        ? `${severAddress}:${port}/${path}`
        : `${severAddress}/${path}`;
      var url = turl.replace(" ", "");
      const timeout = !!options.timeout ? options.timeout : 10000;

      if (!that[url]) {
        that[url] = {
          sync: sync,
          contine: true,
        };
      }
      if (sync) {
        if (!that[url].contine) {
          console.error(`method name : ${url} has not compelte !`);
          if (options.complete) {
            options.complete();
          }
          return;
        }
        that[url].contine = false;
      }
      const headers = options.config.headers;

      wx.request({
        url: url,
        header: headers,
        method: method,
        data: options.data,
        timeout: timeout,
        success: function (res) {
          res.netUrl = url;
          wx.hideLoading();
          if (
            typeof that.resInterceptor == "function" &&
            !that.resInterceptor(res)
          ) {
            return;
          }
          if (options.success) {
            options.success(res.data);
          } else {
            resolve(res.data);
          }
        },
        fail: function (res) {
          // write warning log
          const logger = wx.getLogManager();
          const logStr = JSON.stringify(res);
          logger.warn(
            "NET ERROR :  " +
              {
                url: url,
                res: logStr,
              }
          );

          if (options.fail) {
            options.fail(res);
          } else {
            reject(res);
          }
        },
        complete: function (res) {
          that[url].contine = true;
          if (options.complete) {
            options.complete(res.data);
          }
        },
      });
    });
  }

  /**
   * @description:
   * @param {*} options
   * @return {*}
   */
  uploadTaskByConf(options) {
    const thatApp = getApp();
    if (thatApp.globalData.netErrTips) {
      return console.error("netErrTips");
    }

    const that = this;
    const severAddress = options.config.host;
    // const method = options.config.method;
    const sync = options.config.sync;
    const path = options.config.path;
    const port = options.config.port;

    const filePath = options.filePath;
    const name = options.name;
    var turl = port
      ? `${severAddress}:${port}/${path}`
      : `${severAddress}/${path}`;
    var url = turl.replace(" ", "");
    const timeout = !!options.timeout ? options.timeout : 5000;

    if (!that[url]) {
      that[url] = {
        sync: sync,
        contine: true,
      };
    }
    if (sync) {
      if (!that[url].contine) {
        console.error(`method name : ${url} has not compelte !`);
        if (options.complete) {
          options.complete();
        }
        return;
      }
      that[url].contine = false;
    }
    const headers = options.config.headers;
    // if (options.promise) {
    //     return new Promise((resolve,reject)=>{

    //     });
    // }

    return new Promise((resolve, reject) => {
      wx.uploadFile({
        url: url,
        header: headers,
        filePath: filePath,
        name: name,
        formData: options.data,
        timeout: timeout,
        success: function (res) {
          res.netUrl = url;
          wx.hideLoading();
          if (
            typeof that.resInterceptor == "function" &&
            !that.resInterceptor(res)
          ) {
            return;
          }
          if (options.success) {
            options.success(res.data);
          } else {
            resolve(res.data);
          }
        },
        fail: function (res) {
          // write warning log
          const logger = wx.getLogManager();
          const logStr = JSON.stringify(res);
          logger.warn(
            "NET ERROR :  " +
              {
                url: url,
                res: logStr,
              }
          );

          if (options.fail) {
            options.fail(res);
          } else {
            const urlObj = that[url];
            reject(res);
          }
        },
        complete: function (res) {
          that[url].contine = true;
          if (options.complete) {
            options.complete(res.data);
          }
        },
      });
    });
  }
}

module.exports = YHNetWorking;
